
package com.watabou.gltextures;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.watabou.glwrap.Texture;

import java.util.HashMap;

public class TextureCache {

	public static Context context;

	private static HashMap<Object, SmartTexture> all = new HashMap<Object, SmartTexture>();

	// No dithering, no scaling, 32 bits per pixel
	private static BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

	static {
		bitmapOptions.inScaled = false;
		bitmapOptions.inDither = false;
		bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
	}

	public static SmartTexture createSolid(int color) {
		final String key = "1x1:" + color;

		if (all.containsKey(key)) {

			return all.get(key);

		} else {

			Bitmap bmp = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
			bmp.eraseColor(color);

			SmartTexture tx = new SmartTexture(bmp);
			all.put(key, tx);

			return tx;
		}
	}

	public static SmartTexture createGradient(int... colors) {

		final String key = "" + colors;

		if (all.containsKey(key)) {

			return all.get(key);

		} else {

			Bitmap bmp = Bitmap.createBitmap(colors.length, 1, Bitmap.Config.ARGB_8888);
			for (int i = 0; i < colors.length; i++) {
				bmp.setPixel(i, 0, colors[i]);
			}
			SmartTexture tx = new SmartTexture(bmp);

			tx.filter(Texture.LINEAR, Texture.LINEAR);
			tx.wrap(Texture.CLAMP, Texture.CLAMP);

			all.put(key, tx);
			return tx;
		}

	}

	public static void add(Object key, SmartTexture tx) {
		all.put(key, tx);
	}

	public static SmartTexture get(Object src) {

		if (all.containsKey(src)) {

			return all.get(src);

		} else if (src instanceof SmartTexture) {

			return (SmartTexture) src;

		} else {

			SmartTexture tx = new SmartTexture(getBitmap(src));
			all.put(src, tx);
			return tx;
		}

	}

	public static void clear() {

		for (Texture txt : all.values()) {
			txt.delete();
		}
		all.clear();

	}

	public static void reload() {
		for (SmartTexture tx : all.values()) {
			tx.reload();
		}
	}

	public static Bitmap getBitmap(Object src) {

		try {
			if (src instanceof Integer) {

				return BitmapFactory.decodeResource(
						context.getResources(), (Integer) src, bitmapOptions);

			} else if (src instanceof String) {

				return BitmapFactory.decodeStream(
						context.getAssets().open((String) src), null, bitmapOptions);

			} else if (src instanceof Bitmap) {

				return (Bitmap) src;

			} else {

				return null;

			}
		} catch (Exception e) {

			e.printStackTrace();
			return null;

		}
	}

	public static boolean contains(Object key) {
		return all.containsKey(key);
	}

}
